package com.lw.leetcode.str.b;

/**
 * Created with IntelliJ IDEA.
 * 640. 求解方程
 *
 * @author liw
 * @version 1.0
 * @date 2022/8/10 14:40
 */
public class SolveEquation {


    public static void main(String[] args) {
        SolveEquation test = new SolveEquation();

        // "x=2"
//        String str = "x+5-3+x=6+x-2";

        // "Infinite solutions"
//        String str = "x=x";

        // "x=0"
//        String str = "2x=x";

        // "Infinite solutions"
//        String str = "0x=0";

        // "No solutions"
//        String str = "x=x+2";

        // "x=-1"
        String str = "2x+3x-6x=x+2";

        // "No solution"
//        String str = "1-x+x-x+x=99";

        String s = test.solveEquation(str);
        System.out.println(s);
    }


    public String solveEquation(String equation) {
        String[] split = equation.split("=");
        int[] ints = find(split[0]);
        int[] ints1 = find(split[1]);
        if (ints[0] == ints1[0]) {
            return ints1[1] == ints[1] ? "Infinite solutions" : "No solution";
        }
        return "x=" + (ints1[1] - ints[1]) / (ints[0] - ints1[0]);
    }

    private int[] find(String str) {
        int a = 0;
        int b = 0;
        char[] arr = str.toCharArray();
        int length = str.length();
        int i = 0;
        int item = 0;
        int f = 1;
        while (i < length) {
            char c = arr[i];
            if (c == '+' || c == '-') {
                b += f * item;
                f = 44 - c;
                item = 0;
            } else if (c == 'x') {
                if (item == 0 && (i == 0 || (arr[i - 1] == '+' || arr[i - 1] == '-'))) {
                    item = 1;
                }
                a += f * item;
                item = 0;
            } else {
                item = item * 10 + c - '0';
            }
            i++;
        }
        b += f * item;
        return new int[]{a, b};
    }

}
